/**
 * 2019年1月1日下午11:10:48
 * @author 谢进财
 */
package com.baihang.platform.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author whati
 *
 */
public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {
	private static Logger log = LoggerFactory.getLogger(AjaxFormAuthenticationFilter.class);
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		 if (isLoginRequest(request, response)) {
	            if (isLoginSubmission(request, response)) {
	                if (log.isInfoEnabled()) {
	                    log.info("身份验证成功");
	                }
	                return executeLogin(request, response);
	            } else {
	                if (log.isInfoEnabled()) {
	                    log.info("Login page view.");
	                }
	                //allow them to see the login page ;)
	                return true;
	            }
	        } else {	           
	            if(isAjax(request)){
	            	((HttpServletResponse)response).setStatus(401);
	            	//直接返回错误的状态码，根据状态码进行相应的操作
	            	//response.getWriter().write(JSON.toJSONString("11"));
	            	//在200状态下返回具体的json信息，解析json内容再进行相应的操作
	            }else{
	                this.saveRequestAndRedirectToLogin(request, response);
	            }
	            return false;
	        }
	}
	private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
	//解决未正常退出用户再登录问题
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		/* if (isLoginRequest(request, response))
	        {
	            if (isLoginSubmission(request, response))
	            {
	                //本次用户登陆账号
	                String account = this.getUsername(request);

	                Subject subject = this.getSubject(request, response);
	                //之前登陆的用户
	                User user = (User) subject.getPrincipal();
	                //如果两次登陆的用户不一样，则先退出之前登陆的用户
	                if (account != null && user != null && !account.equals(user.getUserName()))
	                {
	                    subject.logout();
	                }
	            }
	        }
          */
		   if(isLoginRequest(request, response) && isLoginSubmission(request, response)){  
	         
		        return false;  
		    }
	        return super.isAccessAllowed(request, response, mappedValue);
	}
	
}
